<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <style>
    input, textarea {
      border: 1px solid #CCC;
      margin: 0px;
      padding: 0px;
    }

    #body {
      max-width:800px;
      margin:auto;
    }

    #log {
      width:100%;
      height:400px;
    }

    #message {
      width:100%;
      line-height:20px;
    }
  </style>
  <title>PHP Web Socket</title>
  <script src="js/jquery-1.11.3.min.js"></script>
  <script src="js/fancywebsocket.js"></script>
</head>
<body>
  <div id='body'>
    <textarea id='log' name='log' readonly='readonly'></textarea>
    <br/>
    <input type='text' id='message' name='message' />
  </div>

  <script>
    var server;

    function log( text ) {
      $log = $('#log');
      //Add text to log
      $log.append(($log.val()?"\n":'')+text);
      //Autoscroll
      $log[0].scrollTop = $log[0].scrollHeight - $log[0].clientHeight;
    }

    function send( text ) {
      server.send( 'message', text );
    }

    $(document).ready(function() {
      log('Try connecting...');
      server = new FancyWebSocket('ws://127.0.0.1:9321');

      $('#message').keypress(function(e) {
        if ( e.keyCode == 13 && this.value ) {
          log( 'You: ' + this.value );
          send( this.value );

          $(this).val('');
        }
      });

      //Let the user know we're connected
      server.bind('open', function() {
        log( "Connected." );
      });

      //OH NOES! Disconnection occurred.
      server.bind('close', function( data ) {
        log( "Server Disconnected." );
      });

      //Log any messages sent from server
      server.bind('message', function( payload ) {
        log( payload );
      });

      server.connect();
    });
  </script>
</body>
</html>